import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginAPI, getUserProfileAPI, logoutAPI, type UserProfile } from '@/apis/user'
import {
  setStoredToken,
  getStoredToken,
  removeStoredToken,
  setStoredUserProfile,
  getStoredUserProfile,
  removeStoredUserProfile
} from '@/utils/storage'

export const useUserStore = defineStore('user', () => {
  // 状态 - 初始化时从本地存储恢复数据
  const token = ref<string>(getStoredToken() || '')
  const userProfile = ref<UserProfile | null>(getStoredUserProfile() as UserProfile | null)
  const isLogin = computed(() => !!token.value)

  // 登录
  const login = async (loginData: { username: string; password: string }) => {
    try {
      const res = await loginAPI(loginData)
      token.value = res.data.token
      setStoredToken(res.data.token)
      return res
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  const getUserProfile = async () => {
    try {
      const res = await getUserProfileAPI()
      userProfile.value = res.data as unknown as UserProfile
      // 保存用户信息到本地存储
      setStoredUserProfile(res.data)
      return res
    } catch (error) {
      throw error
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await logoutAPI()
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 无论接口是否成功，都清除本地数据
      token.value = ''
      userProfile.value = null
      removeStoredToken()
      removeStoredUserProfile()
    }
  }

  // 清除用户信息
  const clearUserProfile = () => {
    token.value = ''
    userProfile.value = null
    removeStoredToken()
    removeStoredUserProfile()
  }

  return {
    token,
    userProfile,
    isLogin,
    login,
    logout,
    getUserProfile,
    clearUserProfile
  }
})
